import Taro from '@tarojs/taro'
import { View, Text, Button } from '@tarojs/components'
import { useState, useEffect } from 'react'
import { DebtForm } from '../../components/DebtForm'
import { PaymentDetails } from '../../components/PaymentDetails'
import { debtService, debtorService } from '../../utils/cloud'

export default function ReverseDebt() {
  const initialFormData = {
    creditor: '', // 债权人
    monthlyPrincipal: '', // 每月本金
    monthlyInterest: '', // 每月利息
    loanPeriod: '', // 贷款周期（月）
    paymentDate: '', // 首次还款日期
    paidPeriods: '0', // 已还期数
    remainingPeriods: '', // 剩余期数
    totalInterest: '', // 总利息
    totalPrincipal: '', // 总本金
    totalPayment: '', // 共计还款
    remark: '', // 备注
    totalPeriods: '' // 总期数
  }

  const [formData, setFormData] = useState(initialFormData)
  const [creditorOptions, setCreditorOptions] = useState([])
  const [calculation, setCalculation] = useState(null)
  const [showDetails, setShowDetails] = useState(false)
  const [loading, setLoading] = useState(true)

  // 还款方式选项 - 添加这个常量
  const paymentTypeOptions = [
    { label: '等额本息', value: 'equalPayment' },
    { label: '等额本金', value: 'equalPrincipal' },
    { label: '先息后本', value: 'interestFirst' },
    { label: '免息', value: 'noInterest' }
  ]

  useEffect(() => {
    // 从云数据库加载债务人数据
    const loadDebtors = async () => {
      try {
        setLoading(true)
        const result = await debtorService.getDebtors()
        if (!result.success) {
          throw new Error(result.error)
        }

        // 将债务人数据转换为Picker可用的格式
        const options = result.data.map(debtor => ({
          name: `${debtor.name}(${debtor.cardNumber.slice(-4)})`,
          id: debtor._id,
          cardNumber: debtor.cardNumber
        }))

        setCreditorOptions(options)
      } catch (error) {
        console.error('加载债务人数据失败:', error)
        Taro.showToast({
          title: '加载债务人数据失败',
          icon: 'error'
        })
      } finally {
        setLoading(false)
      }
    }

    loadDebtors()
  }, [])

  // 处理输入变化
  const handleInputChange = (value, field) => {
    const newFormData = {
      ...formData,
      [field]: value
    }

    // 如果修改了总期数或已还期数，自动计算剩余期数
    if (field === 'loanPeriod' || field === 'paidPeriods') {
      const total = parseInt(field === 'loanPeriod' ? value : formData.loanPeriod) || 0
      const paid = parseInt(field === 'paidPeriods' ? value : formData.paidPeriods) || 0
      newFormData.remainingPeriods = Math.max(0, total - paid).toString()
    }

    setFormData(newFormData)
  }

  // 处理债权人选择
  const handleCreditorChange = value => {
    const selectedCreditor = creditorOptions[value.detail.value]
    if (selectedCreditor) {
      handleInputChange(selectedCreditor.id, 'creditor')
    }
  }

  // 处理还款方式变化
  const handlePaymentTypeChange = value => {
    const selectedPaymentType = paymentTypeOptions[value.detail.value]
    setFormData({
      ...formData,
      paymentType: selectedPaymentType.value
    })
  }

  // 字段定义
  const fields = [
    {
      name: 'monthlyPrincipal',
      title: '每月本金',
      type: 'digit',
      placeholder: '请输入每月本金',
      required: true
    },
    {
      name: 'monthlyInterest',
      title: '每月利息',
      type: 'digit',
      placeholder: '请输入每月利息',
      required: true
    },
    {
      name: 'loanPeriod',
      title: '贷款周期',
      type: 'number',
      placeholder: '请输入贷款周期(月)',
      required: true
    },
    {
      name: 'paymentDate',
      title: '首次还款日期',
      type: 'date',
      placeholder: '请选择首次还款日期',
      required: true
    },
    {
      name: 'paidPeriods',
      title: '已还期数',
      type: 'number',
      placeholder: '请输入已还期数',
      required: true
    },
    // 为先息后本形式添加总本金字段
    {
      name: 'totalLoanAmount',
      title: '总本金',
      type: 'digit',
      placeholder: '请输入总本金(先息后本时必填)',
      required: false,
      condition: formData => formData.paymentType === 'interestFirst'
    },
    { name: 'remark', title: '备注', type: 'text', placeholder: '请输入备注' }
  ]

  // 表格列定义
  const columns = [
    { key: 'period', title: '期数' },
    { key: 'payment', title: '月供' },
    { key: 'principal', title: '本金' },
    { key: 'interest', title: '利息' },
    { key: 'remainingPrincipal', title: '剩余本金', width: '2' },
    { key: 'paymentDate', title: '还款日', width: '2' },
    {
      key: 'isPaid',
      title: '状态',
      color: 'isPaid',
      width: '2',
      render: value => (value ? '已还款' : '未还款')
    }
  ]

  // 验证必填项
  const validateRequiredFields = () => {
    const requiredFields = [
      { field: 'creditor', name: '债权人' },
      { field: 'monthlyPrincipal', name: '每月本金' },
      { field: 'monthlyInterest', name: '每月利息' },
      { field: 'loanPeriod', name: '贷款周期' },
      { field: 'paymentDate', name: '还款日' },
      { field: 'paidPeriods', name: '已还期数' }
    ]

    // 先息后本模式下检查总本金
    if (formData.paymentType === 'interestFirst') {
      requiredFields.push({ field: 'totalLoanAmount', name: '总本金' })
    }

    for (const { field, name } of requiredFields) {
      if (!formData[field]) {
        Taro.showToast({
          title: `请填写${name}`,
          icon: 'none'
        })
        return false
      }
    }

    return true
  }

  // 计算贷款详情
  const calculateReverseDebt = () => {
    if (!validateRequiredFields()) {
      return
    }

    // 检查先息后本模式下是否填写了总本金
    if (formData.paymentType === 'interestFirst' && !formData.totalLoanAmount) {
      Taro.showToast({
        title: '先息后本模式下请填写总本金',
        icon: 'none'
      })
      return
    }

    const {
      monthlyPrincipal,
      monthlyInterest,
      loanPeriod,
      paymentDate,
      paidPeriods,
      paymentType,
      totalLoanAmount
    } = formData

    // 转换为数字类型
    const principal = parseFloat(monthlyPrincipal)
    const interest = parseFloat(monthlyInterest)
    const period = parseInt(loanPeriod)
    const paid = parseInt(paidPeriods)

    // 计算总金额 - 根据还款方式不同计算方式不同
    let totalPrincipal = 0
    let totalInterest = 0
    let paymentPlan = []

    if (paymentType === 'interestFirst') {
      // 先息后本模式
      totalPrincipal = parseFloat(totalLoanAmount)
      totalInterest = interest * period
    } else {
      // 其他模式
      totalPrincipal = principal * period
      totalInterest = interest * period
    }

    const totalPayment = totalPrincipal + totalInterest
    const remainingPeriods = period - paid

    const annualRate = calculateRealRate(totalPrincipal, interest, period)
    console.log('计算结果:', annualRate)

    // 生成还款计划
    paymentPlan = []
    let remainingPrincipal = totalPrincipal

    // 计算首次还款日期
    const firstPaymentDate = new Date(paymentDate)

    if (paymentType === 'interestFirst') {
      // 先息后本模式的还款计划
      for (let i = 1; i <= period; i++) {
        // 计算当前还款日期
        const currentPaymentDate = new Date(firstPaymentDate)
        currentPaymentDate.setMonth(firstPaymentDate.getMonth() + (i - 1))
        const formattedDate = `${currentPaymentDate.getFullYear()}-${String(currentPaymentDate.getMonth() + 1).padStart(2, '0')}-${String(currentPaymentDate.getDate()).padStart(2, '0')}`

        // 最后一期还本金，之前只还利息
        const currentPrincipal = i === period ? totalPrincipal : 0
        const payment = i === period ? interest + totalPrincipal : interest

        // 添加到还款计划
        paymentPlan.push({
          period: `${i}期`,
          payment: payment.toFixed(2),
          principal: currentPrincipal.toFixed(2),
          interest: interest.toFixed(2),
          remainingPrincipal: i === period ? '0.00' : totalPrincipal.toFixed(2),
          paymentDate: formattedDate,
          isPaid: i <= paid,
          type: 'interestFirst'
        })
      }
    } else {
      // 其他模式的还款计划
      for (let i = 1; i <= period; i++) {
        // 计算当前还款日期
        const currentPaymentDate = new Date(firstPaymentDate)
        currentPaymentDate.setMonth(firstPaymentDate.getMonth() + (i - 1))
        const formattedDate = `${currentPaymentDate.getFullYear()}-${String(currentPaymentDate.getMonth() + 1).padStart(2, '0')}-${String(currentPaymentDate.getDate()).padStart(2, '0')}`

        // 更新剩余本金
        remainingPrincipal = i === 1 ? totalPrincipal : remainingPrincipal - principal

        // 添加到还款计划
        paymentPlan.push({
          period: `${i}期`,
          payment: (principal + interest).toFixed(2),
          principal: principal.toFixed(2),
          interest: interest.toFixed(2),
          remainingPrincipal: Math.max(0, remainingPrincipal - principal).toFixed(2),
          paymentDate: formattedDate,
          isPaid: i <= paid,
          type: 'normal'
        })
      }
    }

    // 更新表单数据
    setFormData({
      ...formData,
      totalPrincipal: totalPrincipal.toFixed(2),
      totalInterest: totalInterest.toFixed(2),
      totalPayment: totalPayment.toFixed(2),
      remainingPeriods: remainingPeriods.toString(),
      totalPeriods: period.toString()
    })

    // 设置计算结果
    const formattedResult = {
      annualRate,
      remainingTotal: totalPayment,
      remainingPrincipal: totalPrincipal,
      remainingInterest: totalInterest,
      monthlyPayment:
        paymentType === 'interestFirst' ? interest.toFixed(2) : (principal + interest).toFixed(2),
      paymentPlan: paymentPlan
    }

    setCalculation(formattedResult)
  }

  // 计算真实利率
  const calculateRealRate = (principal, interest, period) => {
    // 每月本金
    const monthlyPrincipal = principal / period
    // 每月利息
    const monthlyInterest = interest

    // 使用二分法求解真实月利率
    let low = 0
    let high = 1
    const tolerance = 0.0000001
    let guess = (low + high) / 2

    // 最大迭代次数，防止无限循环
    const maxIterations = 1000 // 增加最大迭代次数
    let iteration = 0

    while (high - low > tolerance && iteration < maxIterations) {
      // 计算当前猜测利率下的每月利息
      let calculatedInterest = 0
      let remainingPrincipal = principal

      for (let i = 0; i < period; i++) {
        // 当月利息 = 剩余本金 * 月利率
        const currentInterest = remainingPrincipal * guess
        calculatedInterest += currentInterest
        // 更新剩余本金 (减去固定的月本金)
        remainingPrincipal -= monthlyPrincipal
      }

      // 平均每月利息
      const avgMonthlyInterest = calculatedInterest / period

      // 调整猜测范围
      if (Math.abs(avgMonthlyInterest - monthlyInterest) < tolerance) {
        // 如果足够接近，直接返回结果
        break
      } else if (avgMonthlyInterest > monthlyInterest) {
        high = guess
      } else {
        low = guess
      }

      guess = (low + high) / 2
      iteration++
    }

    // 转换为年化利率并返回百分比形式
    return (guess * 12 * 100).toFixed(2)
  }

  // 保存数据
  const handleSave = async () => {
    if (!validateRequiredFields()) {
      return
    }

    if (!calculation) {
      Taro.showToast({
        title: '请先计算还款计划',
        icon: 'none'
      })
      return
    }

    try {
      // 计算真实利率
      const monthlyPrincipal = parseFloat(formData.monthlyPrincipal)
      const monthlyInterest = parseFloat(formData.monthlyInterest)
      const period = parseInt(formData.loanPeriod)
      const totalPrincipal = monthlyPrincipal * period

      // 使用更准确的方法计算年化利率
      const annualRate = calculateRealRate(totalPrincipal, monthlyInterest, period)

      // 添加新数据
      const newDebt = {
        creditor: formData.creditor,
        loanAmount: formData.totalPrincipal, // 添加总金额字段
        rate: annualRate, // 添加真实利率字段
        monthlyPrincipal: formData.monthlyPrincipal,
        monthlyInterest: formData.monthlyInterest,
        loanPeriod: formData.loanPeriod,
        paymentDate: formData.paymentDate,
        loanDate: formData.paymentDate, // 使用首次还款日期作为借款日期
        paidPeriods: formData.paidPeriods,
        remainingPeriods: formData.remainingPeriods,
        totalInterest: formData.totalInterest,
        totalPrincipal: formData.totalPrincipal,
        totalPayment: formData.totalPayment,
        remark: formData.remark,
        calculation: calculation,
        isReverse: true, // 标记为反向计算的贷款
        paymentType: formData.paymentType || 'equalPayment', // 确保有还款方式字段
        totalPeriods: formData.totalPeriods // 确保有总期数字段
      }

      const result = await debtService.addDebt(newDebt)

      if (result.success) {
        Taro.showToast({
          title: '保存成功',
          icon: 'success'
        })

        // 返回上一页
        setTimeout(() => {
          Taro.navigateTo({ url: '/pages/index/index' })
        }, 1500)
      } else {
        throw new Error(result.error)
      }
    } catch (error) {
      Taro.showToast({
        title: '保存失败',
        icon: 'error'
      })
    }
  }

  return (
    <View className="min-h-screen bg-gray-100 p-4">
      <View className="mb-4 text-center">
        <Text className="text-xl font-bold">反向计算贷款</Text>
      </View>

      <DebtForm
        formData={formData}
        creditorOptions={creditorOptions}
        paymentTypeOptions={paymentTypeOptions}
        handleCreditorChange={handleCreditorChange}
        handlePaymentTypeChange={handlePaymentTypeChange}
        handleInputChange={(value, name) => handleInputChange(value, name)}
        fields={fields}
      >
        {calculation && (
          <View className="mt-4 bg-white p-4 rounded-lg shadow">
            <View className="grid grid-cols-2 gap-2 mb-4">
              <View className="flex flex-col">
                <Text className="text-gray-500">总本金</Text>
                <Text className="text-lg font-bold">{formData.totalPrincipal} 元</Text>
              </View>
              <View className="flex flex-col">
                <Text className="text-gray-500">总利息</Text>
                <Text className="text-lg font-bold">{formData.totalInterest} 元</Text>
              </View>
              <View className="flex flex-col">
                <Text className="text-gray-500">总还款</Text>
                <Text className="text-lg font-bold">{formData.totalPayment} 元</Text>
              </View>
              <View className="flex flex-col">
                <Text className="text-gray-500">剩余期数</Text>
                <Text className="text-lg font-bold">{formData.remainingPeriods} 期</Text>
              </View>
              <View className="flex flex-col col-span-2">
                <Text className="text-gray-500">真实年化利率</Text>
                <Text className="text-lg font-bold text-red-500">{calculation.annualRate}%</Text>
              </View>
            </View>
          </View>
        )}

        <View className="flex justify-between mt-4 p-4">
          <Button
            onClick={calculateReverseDebt}
            className="bg-blue-500 text-white rounded-md py-2 px-4 mr-2"
          >
            计算
          </Button>
          <Button
            onClick={handleSave}
            className="bg-green-500 text-white rounded-md py-2 px-4"
            disabled={!calculation}
          >
            保存
          </Button>
        </View>
      </DebtForm>

      {calculation && (
        <PaymentDetails
          details={calculation}
          columns={columns}
          showDetails={showDetails}
          setShowDetails={setShowDetails}
        />
      )}
    </View>
  )
}
